Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Checkit is a validation library for JavaScript that allows you to define and enforce rules for your data. It is particularly useful for validating user input in web applications.
Basic Validation
This feature allows you to define basic validation rules for your data. In this example, the 'name' field must be present and contain only alphabetic characters, while the 'age' field must be present, an integer, and at least 18.
const Checkit = require('checkit');
const rules = new Checkit({
name: ['required', 'alpha'],
age: ['required', 'integer', 'min:18']
});
rules.run({ name: 'John', age: 25 })
.then(validated => console.log('Validated:', validated))
.catch(err => console.error('Validation failed:', err));
Custom Validation
This feature allows you to define custom validation rules. In this example, a custom rule is added to Checkit's Validator prototype, which checks if the value of 'customField' is 'customValue'.
const Checkit = require('checkit');
Checkit.Validator.prototype.customRule = function(val) {
if (val !== 'customValue') {
throw new Error('Value must be customValue');
}
};
const rules = new Checkit({
customField: ['customRule']
});
rules.run({ customField: 'customValue' })
.then(validated => console.log('Validated:', validated))
.catch(err => console.error('Validation failed:', err));
Asynchronous Validation
This feature allows you to define asynchronous validation rules. In this example, an asynchronous rule is added to Checkit's Validator prototype, which checks if the value of 'asyncField' is 'asyncValue' after a delay.
const Checkit = require('checkit');
Checkit.Validator.prototype.asyncRule = function(val) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (val === 'asyncValue') {
resolve();
} else {
reject(new Error('Value must be asyncValue'));
}
}, 1000);
});
};
const rules = new Checkit({
asyncField: ['asyncRule']
});
rules.run({ asyncField: 'asyncValue' })
.then(validated => console.log('Validated:', validated))
.catch(err => console.error('Validation failed:', err));
Joi is a powerful schema description language and data validator for JavaScript. It allows you to create blueprints or schemas for JavaScript objects to ensure validation of key information. Compared to Checkit, Joi offers a more extensive set of built-in validation rules and better integration with modern JavaScript frameworks.
Validator is a library of string validators and sanitizers. It is highly performant and provides a wide range of validation and sanitization functions. Unlike Checkit, which is more focused on object validation, Validator is specialized in string validation.
Yup is a JavaScript schema builder for value parsing and validation. It is similar to Joi but is more lightweight and has a more modern API. Yup is often used in React applications for form validation. Compared to Checkit, Yup offers better integration with modern front-end frameworks and a more intuitive API.
A DOM-independent validation library for Node.js and the browser.
It allows you to seamlessly validate full javascript objects, defining custom messages, labels, and validations, with full support for asynchronous validations with promises. It supports conditional validations, and has powerful, consistent error structuring and utility methods for manipulating your errors' output any way you can imagine.
var mainRules = Checkit(rules);
mainRules
.run(obj)
.then(function(validatedFields) {
console.log('The fields: ' + _.keys(validatedFields).join(', ') + ' were validated!');
})
.caught(Checkit.Error, function(err) {
$("#errors").html(err.map(function(val, key) {
return '<li>' key + ': ' + val.first().message + '</li>';
}).join(''));
});
Checkit has three hard dependencies:
For more reading on promises, and the Bluebird API, take a look at following links:
Installing with node.js npm install checkit
, your dependencies should be taken care of automatically.
The easiest way to use the library is with AMD, but if you prefer to use browser globals, you'll need to include all dependencies before using the library:
<script src="/create-error.js"></script>
<script src="/lodash.js"></script> <!-- (or underscore.js) -->
<script src="/bluebird.js"></script>
<script src="/checkit.js"></script>
If you'd prefer not to use "bluebird" as the promise implementation in the browser, you should change the AMD path to a different promise library, so that Checkit.Promise
is set to an object containing two methods, resolve
and all
.
The subsitute must be an "A+" promise implementation (jQuery won't cut it), but when.js
or Q
would both be suitable to swap out; if using browser globals, like the following:
Checkit.Promise = Q;
The main Checkit
constructor may be called with or without the new
keyword, taking a hash of fields/rules for these fields to be validated.
Used to specify the default language key for using a particular language block.
var checkit = new Checkit({
firstName: 'required',
lastName: 'required',
email: ['required', 'email']
});
var body = {
email: 'test@example.com',
firstName: 'Tim',
lastName: 'Griesser',
githubUsername: 'tgriesser'
};
checkit.run(body).then(function(validated) {
console.log(validated);
}).catch(Checkit.Error, function(err) {
console.log(err.toJSON());
})
Checkit.check('email', email, ['required', 'validEmail'])
.catch(function(err) {
console.log(err.message)
});
An object containing default language
Validation Name | Description |
---|---|
accepted | The value must be yes, on, or 1. This is useful for validating "Terms of Service" acceptance. |
alpha | The value must be entirely alphabetic characters. |
alphaDash | The value may have alpha-numeric characters, as well as dashes and underscores. |
alphaNumeric | The value must be entirely alpha-numeric characters. |
alphaUnderscore | The value must be entirely alpha-numeric, with underscores but not dashes. |
arguments | The value must be a javascript "arguments" object. |
array | The value must be a valid array object. |
base64 | The value must be a base64 encoded value. |
between:min:max | The value must have a size between the given min and max. |
boolean | The value must be a javascript boolean. |
contains:value | The value must contain the value. For a string, it does an "indexOf" check, an array "_.indexOf" and for an object "_.has". |
date | The value must be a valid date object. |
different:fieldName | The given field must be different than the `fieldName` under validation. |
The field must be a valid formatted e-mail address. | |
empty | The value under validation must be empty; either an empty string, an empty, array, empty object, or a falsy value. |
exactLength:value | The field must have the exact length of "val". |
exists | The value under validation must not be undefined. |
finite | The value under validation must be a finite number. |
function | The value under validation must be a function. |
greaterThan:value | The value under validation must be "greater than" the given value. |
greaterThanEqualTo:value | The value under validation must be "greater than" or "equal to" the given value. |
integer | The value must have an integer value. |
ipv4 | The value must be formatted as an IP address. |
lessThan:value | The value must be "less than" the specified value. |
lessThanEqualTo:value | The value must be "less than" or "equal to" the specified value. |
luhn | The given value must pass a basic luhn (credit card) check regular expression. |
matchesField:fieldName | The value must exactly match the value of another `fieldName` under validation. |
max:value | The value must be less than a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule. |
maxLength:value | The value must have a length property which is less than or equal to the specified value. Note, this may be used with both arrays and strings. |
min:value | The value must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule. |
minLength:value | The value must have a length property which is greater than or equal to the specified value. Note, this may be used with both arrays and strings. |
NaN | The value must be NaN. |
natural | The value must be a natural number (a number greater than or equal to 0). |
naturalNonZero | The value must be a natural number, greater than or equal to 1. |
null | The value must be null. |
number | The value must be a javascript Number. |
numeric | The value must have a numeric value. |
object | The value must pass an _.isObject check. |
plainObject | The value must be an object literal. |
regExp | The value must be a javascript RegExp object. |
required | The value must be present in the input data. |
url | The value must be formatted as an URL. |
uuid | Passes for a validly formatted UUID. |
Sometimes you may wish to require a given field conditionally, for example require a field only if another field has a greater value than 100. Or you may need two fields to have a given value only when another field is present. Adding these validation rules doens't have to be a pain. First, create a Checkit
instance with the main rules that never change:
var checkit = new Checkit({
firstName: ['required'],
lastName: ['required'],
email: ['required', 'email']
});
Then use the maybe
method to add additional rules:
The first of the maybe
method is the hash of validation fields / settings, similar to the main Checkit
object. The second argument is a function, evaluated with the object being validated, and if it returns explicitly true
or with a promise fulfilling with true
, it will add an additional validator to the Checkit
object.
This method makes building complex conditional validations a snap.
// In this example, the "authorBio" field is only required if there are
// more than 5 books specified in the input object
checkit.maybe({authorBio: ['required', 'max:500']}, function(input) {
return input.books > 5;
});
First, and simplest, you can specify a function on the validation array for a property. For example:
{
email: ['email', function(val) {
return knex('accounts').where('email', '=', val).then(function(resp) {
if (resp.length > 0) throw new Error('The email address is already in use.')
})
}]
}
You may also specify an object in one of the validator slots, specifying at the minimum a rule, and optionally params, label, and message.
{
email: {
rule: 'email',
label: 'Email'
},
first_name: [{
rule: 'required',
message: 'You must supply a first name value!!'
}, {
rule: 'minLength:3',
label: 'first name of this application'
}],
arr: {
rule: 'contains', // different behavior than "contains:10"
params: [10]
}
}
Second, you may add a custom validator to the Checkit.Validators
object, returning a boolean value or a promise.
Checkit.Validators.unused = function(val, table, column) {
return knex(table).where(column, '=', val).then(function(resp) {
if (resp.length > 0) {
throw new Error('The ' + table + '.' + column + ' field is already in use.');
}
});
}
{
email: ['email', 'unused:accounts:email']
}
One of the main features of Checkit
is the error handling; By extending the error object with utility methods from underscore, the errors are even easier to work with.
The main Error object, Checkit.Error
is returned from the has several helper methods & properties, as well as a number of utility methods:
The "errors" property of a Checkit.Error
object is a hash of errors for each of the fields which are considered "invalid" in any way by the validation rules. The keys in this hash are the invalid fields, and the values are Checkit.FieldError objects, which in-turn have an errors
attribute, an array containing errors for each failed rule.
The get
method returns the Checkit.FieldError
object for a specific key, or undefined
if one does not exist.
Useful for debugging, the toString
method converts the Checkit
error into a human readable representation of the failed validation. If the flat
argument is passed as a "truthy" value, it will output only the first ValidationError
in the FieldError
; otherwise it will output each validation message in a comma separated string.
Converts the current error object to a json representation of the error, for easy use/refinement elsewhere. For other methods, such as map, reduce, each, see the utility methods section.
A FieldError
is an error that contains all of the sub-errors for the validation of an individual item in the validated hash.
The errors
property of a FieldError
is
A ValidationError
is the result of an individual error in the field rule.
The following methods are underscore methods proxied to the Checkit.Error
and Checkit.FieldError
objects, for easy manipulation of the .errors
object contained in each.
The Checkit.labelTransform
method takes a function which
CheckIt
is now renamed Checkit
validations
and target
arguments, so the syntax is now Checkit(validations).run(input)
rather than Checkit(input).run(validations)
, allowing for re-use of the validation objects.Initial release
FAQs
Simple validations for node and the browser.
The npm package checkit receives a total of 128,837 weekly downloads. As such, checkit popularity was classified as popular.
We found that checkit demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.